<template>
  <!-- 项目管理：excel文档内容 -->
  <div style="width:100%;background:#FFF;">
    <el-row :gutter="10" style="width:96%;margin:20px auto 15px;">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini"
          :disabled="isEditing" @click="addContentInfo">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-sort" size="mini"
          :disabled="sortPartVisible && !contentList.length" @click="changeSort">变更排序</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-finished" size="mini"
          @click="startSaveSort" v-show="sortPartVisible">保存排序</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-close" size="mini"
          @click="cancelChangeSort" v-show="sortPartVisible">取消排序</el-button>
      </el-col>
    </el-row>
    <!-- <table class="el-table">
      <colgroup>
        <col v-for="(vo, index) in heading" :key="index" :width="vo.width" />
      </colgroup>
      <thead>
        <tr>
          <td v-for="(vo, index) in heading" :key="index">{{ vo.name }}</td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(vo, index) in contentList" :key="index">
          <td>{{ vo[heading[index].name] }}</td>
          <td>
            <el-button type="text" icon="el-icon-edit" @click="editContentInfo(vo, index)">修改</el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteContentInfo(vo, index)">删除</el-button>
          </td>
        </tr>
      </tbody>
    </table> -->

    <div v-if="contentList.length">
      <el-table :data="contentList" style="width:96%;margin:6px auto;">
        <el-table-column label="排序" align="center" min-width="50">
          <template slot-scope="scope">
            <input type="hidden" :id="'sortPart_'+scope.row.contId" class="sortPart" />
            <input type="number" :id="'sortNum_'+scope.row.sortNum" class="el-input sortInput" v-model="scope.row.sortNum" v-if="sortPartVisible" />
            <span v-else>{{ scope.row.sortNum }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="(vo, index) in heading" :key="index" :label="vo.name" align="center" :min-width="vo.width">
          <template slot-scope="scope">
            <span v-if="scope.row.content[vo.param]">{{ scope.row.content[vo.param] }}</span>
            <span v-else></span>
          </template>
          <!-- <template slot-scope="scope">{{ Object.values(scope.row.content)[index] }}</template> -->
        </el-table-column>
        <el-table-column label="是否正在编辑" align="center" min-width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isEditing?'success':'warning'">{{ scope.row.isEditing?"是":"否" }}</el-tag>
            <span style="margin-left:4px;" v-show="scope.row.isEditing">【当前编辑人：{{ scope.row.editingBy }}】</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" :disabled="scope.row.isEditing&&scope.row.editingBy!=name?true:false" @click="editContentInfo(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-delete" :disabled="scope.row.isEditing&&scope.row.editingBy!=name?true:false" @click="deleteContentInfo(scope.row.contId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="noData" v-else>暂无信息</div>

    <!-- 新增|编辑-start -->
    <el-dialog :title="contId?'编辑':'新增'" :append-to-body="true" :close-on-click-modal="false" :before-close="beforeCloseSet"
               :visible.sync="contentVisible" :width="device=='mobile'?'98%':'762px'">
      <el-form ref="contentForm" :class="device=='mobile'?'mobileContentForm':'contentForm'" :model="contentForm" :inline="device=='mobile'?false:true" label-width="150px">
        <el-form-item v-for="(vo, index) in heading" :key="index" :label="vo.name" :prop="vo.param">
          <el-input v-model="currentContent[vo.param]" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeContentPage('quit')">取 消</el-button>
        <el-button type="primary" @click="saveContentInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增|编辑-end -->
  </div>
</template>

<script>
  import { Loading } from 'element-ui';
  import { mapGetters } from 'vuex';
  import { listContentInfo, contentInfoSave, detailContentInfo, deleteContentInfo, setSort, setIsEditing, cancelIsEditing } from "@/api/project/contentInfo";

  export default {
    name: 'ProjectExcelContent',
    data(){
      return {
        projectId:this.$route.query.projectId,
        heading:JSON.parse(this.$route.query.heading),
        contentList:[],

        contentVisible:false,
        contId:"",
        contentForm:{},
        currentContent:{},
        sortPartVisible:false,
        isEditing:false,  // 是否正在编辑

        // websocket
        wsObj:null,
        wsUrl:""
      }
    },
    created(){
      this.getContentInfo();
      
      this.wsUrl = process.env.VUE_APP_WEBSOCKET_URL+"/ws/editing/"+this.projectId+"/"+this.name;
      this.initWebsocket();
    },
    activated(){
      this.projectId = this.$route.query.projectId;
    },
    computed: {
      ...mapGetters([
        'nickName', 'name', 'device'
      ])
    },
    watch:{
      projectId(){
        this.getContentInfo();
      }
    },
    methods:{
      // websocket初始化
      initWebsocket(){
        this.wsObj = new WebSocket(this.wsUrl);

        this.wsObj.onopen = ()=>{}

        this.wsObj.onerror = ()=>{
          this.wsObj = new WebSocket(this.wsUrl);
        }

        this.wsObj.onclose = ()=>{
          this.wsObj = new WebSocket(this.wsUrl);
        }

        this.wsObj.onmessage = (e)=>{
          let data = JSON.parse(e.data);
          console.log("data", data);
          this.$notify({
            title: '成功',
            message: data.msg,
            type: 'success'
          });
          detailContentInfo(data.contId).then(ret=>{
            if(ret.code == 200){
              if(this.contentList.length){
                this.contentList.map((vo, index)=>{
                  if(vo.contId == data.contId){
                    ret.data.content = JSON.parse(ret.data.content);
                    this.$set(this.contentList, index, ret.data);
                  }
                })
              }
            }else{}
          })
        }
      },

      // 获取文档内容
      getContentInfo(){
        let loadingInstance = Loading.service({ fullscreen: true, background:"rgba(0,0,0,0.5)" });
        listContentInfo({
          projectId:this.projectId
        }).then(ret=>{
          if(ret.code == 200){
            this.contentList = [];
            ret.rows.map((vo, i)=>{
              vo.index = i+1;
              vo.content = JSON.parse(vo.content);
              this.contentList.push(vo);
            })
          }else{
            this.$message.error(ret.msg);
          }
          loadingInstance.close();
        })
        .catch(err=>{
          console.log(err);
          loadingInstance.close();
        })
      },

      // 新增
      addContentInfo(){
        this.contId = "";
        this.contentForm = {};
        this.currentContent = {};
        this.contentVisible = true;
        this.contentForm.sortNum = this.contentList.length?this.contentList.length+1:1;
        console.log("contentForm", this.contentForm);
      },

      // 编辑信息
      editContentInfo(info){
        detailContentInfo(info.contId).then(ret=>{
          if(ret.code == 200){
            if(!ret.data.isEditing){
              this.contentVisible = true;
              this.contId = info.contId;
              this.setIsEditing(info.contId);
              this.currentContent = JSON.parse(ret.data.content);
              this.contentForm = {
                content:JSON.parse(ret.data.content),
                sortNum:ret.data.sortNum,
                isEditing:ret.data.isEditing,
                editingBy:ret.data.editingBy
              };
            }else{
              this.$message.warning("当前有人正在编辑，请稍后");
            }
          }else{}
        }).catch();
      },

      // 删除信息
      deleteContentInfo(contId){
        detailContentInfo(contId).then(res=>{
          if(res.code == 200){
            if(!res.data.isEditing){
              this.$confirm("您确定要删除该信息？！", "提示", {
                confirmButtonText:"删除",
                cancelButtonText:"取消",
                type:"warning"
              }).then(()=>{
                this.setIsEditing(contId);
                deleteContentInfo(contId).then(ret=>{
                  if(ret.code == 200){
                    this.$message.success("删除成功！");
                    this.getContentInfo();
                  }else{
                    this.$message.error(ret.msg);
                  }
                }).catch(err=>{
                  console.log(err);
                })
              }).catch(()=>{
                this.cancelIsEditing(contId);
              })
          }else{
              this.$message.warning("当前有人正在编辑，请稍后");
            }
          }else{}
        })
      },

      // 设置编辑状态
      setIsEditing(contId){
        setIsEditing({
          contId:contId
        }).then(ret=>{
          console.log("ret", ret)
          if(ret.code == 200){}else{}
        })
      },

      // 取消设置编辑状态
      cancelIsEditing(contId){
        cancelIsEditing({
          contId:contId
        }).then(ret=>{}).catch(err=>{})
      },

      // 保存
      saveContentInfo(){
        let loadingInstance = Loading.service({ fullscreen: true, background:"rgba(0,0,0,0.5)" });
        let params = {
          content:JSON.stringify(this.currentContent)
        };
        params.projectId = this.projectId;
        if(!this.contId){
          params.sortNum = this.contentList.length?this.contentList.length+1:1;
        }else{
          params.contId = this.contId;
          params.sortNum = this.contentForm.sortNum;
        }
        console.log("params",params)

        contentInfoSave(params).then(ret=>{
          loadingInstance.close();
          if(ret.code == 200){
            this.$message.success("保存成功！");
            this.$refs.contentForm.resetFields();
            this.closeContentPage();
            this.wsObj.send(this.name+"刚刚编辑完了文档")
            setTimeout(() => {
              this.getContentInfo();
            }, 10);
          }else{
            this.$message.error(ret.msg);
          }
        }).catch(err=>{
          console.log(err);
          loadingInstance.close();
        })
      },

      beforeCloseSet(done){
        if(this.contId) this.cancelIsEditing(this.contId);
        setTimeout(() => {
          done();
        }, 100);
      },

      // 关闭
      closeContentPage(type){
        if(this.contId && type=='quit') this.cancelIsEditing(this.contId);
        this.contId = "";
        this.heading.map(vo=>{
          this.contentForm[vo.param] = null;
          this.currentContent[vo.param] = null;
        })
        this.contentVisible = false;
      },

      // 变更排序
      changeSort(){
        this.sortPartVisible = true;
        this.originalContentList = JSON.parse(JSON.stringify(this.currentContentList));
      },
      startSaveSort(){
        this.$confirm("您确定要保存当前已更改的排序？！", "提示", {
          confirmButtonText:"保存",
          cancelButtonText:"取消",
          type:"warning"
        }).then(()=>{
          this.setSort();
        }).catch()
      },
      setSort(){
        let contIdArr = document.getElementsByClassName("sortPart");
        let sortNumArr = document.getElementsByClassName("sortInput");
        let sortArr = [];
        for(let i = 0; i < contIdArr.length; i++){
          if(!sortNumArr[i].id.split("_")[1]){
            this.$message.warning("您还有部分内容的排序未填写！");
            return false;
          }
          sortArr.push({
            contId:contIdArr[i].id.split("_")[1],
            sortNum:Number(sortNumArr[i].id.split("_")[1])
          })
          if(i == contIdArr.length-1){
            setSort(sortArr).then(ret=>{
              if(ret.code == 200){
                this.$message.success("排序已更新");
                this.sortPartVisible = false;
                this.getContentInfo();
              }else{
                this.$message.error(ret.msg);
              }
            }).catch(err=>{})
          }
        }
      },

      // 取消排序
      cancelChangeSort(){
        this.sortPartVisible = false;
        this.currentContentList = JSON.parse(JSON.stringify(this.originalContentList));
        console.log(this.originalContentList)
        console.log(this.currentContentList);
      },
    },
    destroyed(){
      if(this.wsObj){
        this.wsObj.close();
        this.wsObj = null;
      }
    }
  }
</script>

<style scoped>
  #noData{
    width:100px;
    height:24px;
    line-height:24px;
    text-align:center;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
  }
  .contentForm >>> .el-input{
    width:561px;
  }
  .mobileContentForm >>> .el-input{
    width:100%;
  }
</style>